<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>交易记录 - 虚拟银行系统</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <link rel="stylesheet" href="/css/main.css">
  <style>
    /* Transactions page specific styles */
    .page-header {
      margin-bottom: var(--spacing-lg);
    }
    
    .page-title {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: var(--spacing-xs);
    }
    
    .page-subtitle {
      color: var(--light-text);
    }
    
    .filter-section {
      display: flex;
      flex-wrap: wrap;
      gap: var(--spacing-md);
      margin-bottom: var(--spacing-lg);
    }
    
    .filter-item {
      flex: 1;
      min-width: 200px;
    }
    
    .date-range {
      display: flex;
      align-items: center;
    }
    
    .date-range-separator {
      margin: 0 var(--spacing-xs);
    }
    
    .transaction-type-badge {
      display: inline-block;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: 500;
    }
    
    .transaction-type-recharge {
      background-color: rgba(82, 196, 26, 0.1);
      color: var(--success-color);
    }
    
    .transaction-type-withdraw {
      background-color: rgba(245, 34, 45, 0.1);
      color: var(--error-color);
    }
    
    .transaction-type-transfer {
      background-color: rgba(24, 144, 255, 0.1);
      color: var(--info-color);
    }
    
    .transaction-type-payment {
      background-color: rgba(250, 173, 20, 0.1);
      color: var(--warning-color);
    }
    
    .transaction-type-refund {
      background-color: rgba(138, 43, 226, 0.1);
      color: #8a2be2;
    }
    
    .transaction-status-badge {
      display: inline-block;
      padding: 2px 6px;
      border-radius: 10px;
      font-size: 12px;
      font-weight: 500;
    }
    
    .transaction-status-processing {
      background-color: rgba(250, 173, 20, 0.1);
      color: var(--warning-color);
    }
    
    .transaction-status-success {
      background-color: rgba(82, 196, 26, 0.1);
      color: var(--success-color);
    }
    
    .transaction-status-failed {
      background-color: rgba(245, 34, 45, 0.1);
      color: var(--error-color);
    }
    
    .transaction-amount {
      font-weight: 600;
    }
    
    .amount-positive {
      color: var(--success-color);
    }
    
    .amount-negative {
      color: var(--error-color);
    }
    
    .pagination {
      display: flex;
      justify-content: center;
      margin-top: var(--spacing-lg);
    }
    
    .page-item {
      margin: 0 var(--spacing-xs);
    }
    
    .page-link {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 32px;
      height: 32px;
      border-radius: 4px;
      background-color: white;
      border: 1px solid var(--border-color);
      color: var(--text-color);
      transition: all 0.3s;
    }
    
    .page-link:hover {
      border-color: var(--secondary-color);
      color: var(--secondary-color);
    }
    
    .page-item.active .page-link {
      background-color: var(--secondary-color);
      border-color: var(--secondary-color);
      color: white;
    }
    
    .page-item.disabled .page-link {
      color: var(--light-text);
      pointer-events: none;
    }
    
    .empty-state {
      text-align: center;
      padding: var(--spacing-lg);
      color: var(--light-text);
    }
    
    .empty-state-icon {
      font-size: 48px;
      margin-bottom: var(--spacing-md);
      color: var(--divider-color);
    }
    
    /* Transaction Detail Modal */
    .transaction-detail-item {
      display: flex;
      margin-bottom: var(--spacing-md);
    }
    
    .transaction-detail-label {
      width: 120px;
      color: var(--light-text);
      flex-shrink: 0;
    }
    
    .transaction-detail-value {
      font-weight: 500;
    }
    
    .transaction-detail-amount {
      font-size: 24px;
      font-weight: 600;
      text-align: center;
      margin: var(--spacing-lg) 0;
    }
    
    .amount-positive {
      color: var(--success-color);
    }
    
    .amount-negative {
      color: var(--error-color);
    }
    
    @media (max-width: 768px) {
      .table th:nth-child(3),
      .table td:nth-child(3),
      .table th:nth-child(4),
      .table td:nth-child(4) {
        display: none;
      }
    }
    
    @media (max-width: 576px) {
      .table th:nth-child(5),
      .table td:nth-child(5) {
        display: none;
      }
      
      .filter-section {
        flex-direction: column;
      }
      
      .filter-item {
        width: 100%;
      }
    }
  </style>
</head>
<body>
  <div class="app-wrapper">
    <!-- Top Navigation Bar -->
    <div id="top-navbar"></div>
    
    <div class="main-container">
      <!-- Sidebar -->
      <div id="sidebar"></div>
      
      <!-- Main Content -->
      <div class="content">
        <div class="page-header">
          <h1 class="page-title">交易记录</h1>
          <p class="page-subtitle">查询和管理您的交易记录</p>
        </div>
        
        <!-- Filter Section -->
        <div class="card mb-4">
          <div class="card-header">
            <h2 class="card-title">筛选条件</h2>
          </div>
          <div class="card-body">
            <div class="filter-section">
              <div class="filter-item">
                <label class="form-label">交易类型</label>
                <select class="form-control" id="transaction-type">
                  <option value="">全部</option>
                  <option value="1">充值</option>
                  <option value="2">提现</option>
                  <option value="3">转账</option>
                  <option value="4">支付</option>
                  <option value="5">退款</option>
                </select>
              </div>
              
              <div class="filter-item">
                <label class="form-label">交易状态</label>
                <select class="form-control" id="transaction-status">
                  <option value="">全部</option>
                  <option value="0">处理中</option>
                  <option value="1">成功</option>
                  <option value="2">失败</option>
                </select>
              </div>
              
              <div class="filter-item">
                <label class="form-label">日期范围</label>
                <div class="date-range">
                  <input type="date" class="form-control" id="start-date">
                  <span class="date-range-separator">至</span>
                  <input type="date" class="form-control" id="end-date">
                </div>
              </div>
              
              <div class="filter-item d-flex align-items-end">
                <button class="btn btn-primary" id="search-btn">
                  <i class="fas fa-search mr-1"></i> 查询
                </button>
                <button class="btn btn-outline ml-2" id="reset-btn">
                  <i class="fas fa-redo mr-1"></i> 重置
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Transactions Table -->
        <div class="card">
          <div class="card-header">
            <h2 class="card-title">交易记录</h2>
            <div class="card-header-actions">
              <button class="btn btn-outline btn-sm" id="export-btn">
                <i class="fas fa-download mr-1"></i> 导出
              </button>
            </div>
          </div>
          <div class="card-body">
            <div class="table-container">
              <table class="table" id="transactions-table">
                <thead>
                  <tr>
                    <th>交易流水号</th>
                    <th>交易类型</th>
                    <th>交易对象</th>
                    <th>交易时间</th>
                    <th>交易金额</th>
                    <th>交易后余额</th>
                    <th>状态</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody id="transactions-list">
                  <tr>
                    <td colspan="8">
                      <div class="loader-container">
                        <div class="loader"></div>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- Pagination -->
            <div class="pagination" id="pagination">
              <!-- Pagination will be generated here -->
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Transaction Detail Modal -->
    <div class="modal-backdrop" id="detail-modal" style="display: none;">
      <div class="modal">
        <div class="modal-header">
          <h3 class="modal-title">交易详情</h3>
          <button class="modal-close" id="detail-close">&times;</button>
        </div>
        <div class="modal-body">
          <div class="transaction-detail-amount" id="detail-amount">¥0.00</div>
          
          <div class="transaction-detail-item">
            <div class="transaction-detail-label">交易流水号</div>
            <div class="transaction-detail-value" id="detail-trade-no">-</div>
          </div>
          <div class="transaction-detail-item">
            <div class="transaction-detail-label">交易类型</div>
            <div class="transaction-detail-value" id="detail-trade-type">-</div>
          </div>
          <div class="transaction-detail-item">
            <div class="transaction-detail-label">交易对象</div>
            <div class="transaction-detail-value" id="detail-target">-</div>
          </div>
          <div class="transaction-detail-item">
            <div class="transaction-detail-label">交易渠道</div>
            <div class="transaction-detail-value" id="detail-channel">-</div>
          </div>
          <div class="transaction-detail-item">
            <div class="transaction-detail-label">交易时间</div>
            <div class="transaction-detail-value" id="detail-time">-</div>
          </div>
          <div class="transaction-detail-item">
            <div class="transaction-detail-label">交易状态</div>
            <div class="transaction-detail-value" id="detail-status">-</div>
          </div>
          <div class="transaction-detail-item">
            <div class="transaction-detail-label">交易后余额</div>
            <div class="transaction-detail-value" id="detail-balance">-</div>
          </div>
          <div class="transaction-detail-item">
            <div class="transaction-detail-label">备注</div>
            <div class="transaction-detail-value" id="detail-remark">-</div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" id="detail-close-btn">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Scripts -->
  <script src="/js/utils/Utils.js"></script>
  <script src="/js/components/Toast.js"></script>
  <script src="/js/services/ApiService.js"></script>
  <script src="/js/components/TopNavBar.js"></script>
  <script src="/js/components/SideBar.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Check if user is authenticated
      if (ApiService.redirectIfNotAuthenticated()) {
        return;
      }
      
      // Initialize components
      const topNavBar = new TopNavBar();
      topNavBar.init();
      
      const sideBar = new SideBar();
      sideBar.init('transactions');
      
      // Filter elements
      const typeSelect = document.getElementById('transaction-type');
      const statusSelect = document.getElementById('transaction-status');
      const startDateInput = document.getElementById('start-date');
      const endDateInput = document.getElementById('end-date');
      const searchBtn = document.getElementById('search-btn');
      const resetBtn = document.getElementById('reset-btn');
      const exportBtn = document.getElementById('export-btn');
      
      // Table elements
      const transactionsTable = document.getElementById('transactions-table');
      const transactionsList = document.getElementById('transactions-list');
      const pagination = document.getElementById('pagination');
      
      // Modal elements
      const detailModal = document.getElementById('detail-modal');
      const detailClose = document.getElementById('detail-close');
      const detailCloseBtn = document.getElementById('detail-close-btn');
      const detailAmount = document.getElementById('detail-amount');
      const detailTradeNo = document.getElementById('detail-trade-no');
      const detailTradeType = document.getElementById('detail-trade-type');
      const detailTarget = document.getElementById('detail-target');
      const detailChannel = document.getElementById('detail-channel');
      const detailTime = document.getElementById('detail-time');
      const detailStatus = document.getElementById('detail-status');
      const detailBalance = document.getElementById('detail-balance');
      const detailRemark = document.getElementById('detail-remark');
      
      // Pagination state
      let currentPage = 1;
      const pageSize = 10;
      let totalPages = 1;
      
      // Filter state
      let filterParams = {
        page: currentPage,
        size: pageSize
      };
      
      // Initialize date inputs with last 30 days
      function initDateInputs() {
        const today = new Date();
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(today.getDate() - 30);
        
        endDateInput.valueAsDate = today;
        startDateInput.valueAsDate = thirtyDaysAgo;
      }
      
      // Initialize
      initDateInputs();
      loadTransactions();
      
      // Load transactions with filters
      function loadTransactions() {
        // Show loading
        transactionsList.innerHTML = `
          <tr>
            <td colspan="8">
              <div class="loader-container">
                <div class="loader"></div>
              </div>
            </td>
          </tr>
        `;
        
        // Prepare query parameters
        const params = { ...filterParams };
        
        ApiService.get('/api/transaction/list', params)
          .then(response => {
            if (response.code === 0 && response.data) {
              const { total, list } = response.data;
              
              // Update pagination
              totalPages = Math.ceil(total / pageSize);
              renderPagination();
              
              // Render transactions
              renderTransactions(list);
            } else {
              throw new Error(response.message || '获取交易记录失败');
            }
          })
          .catch(error => {
            console.error('Error loading transactions:', error);
            transactionsList.innerHTML = `
              <tr>
                <td colspan="8">
                  <div class="empty-state">
                    <i class="fas fa-exclamation-circle empty-state-icon"></i>
                    <p>加载失败，请稍后再试</p>
                  </div>
                </td>
              </tr>
            `;
          });
      }
      
      // Render transactions list
      function renderTransactions(transactions) {
        if (!transactions || transactions.length === 0) {
          transactionsList.innerHTML = `
            <tr>
              <td colspan="8">
                <div class="empty-state">
                  <i class="fas fa-file-alt empty-state-icon"></i>
                  <p>暂无交易记录</p>
                </div>
              </td>
            </tr>
          `;
          return;
        }
        
        let html = '';
        
        transactions.forEach(transaction => {
          // Determine amount class (positive/negative)
          const isIncome = [1, 5].includes(transaction.tradeType); // 充值或退款
          const amountClass = isIncome ? 'amount-positive' : 'amount-negative';
          const amountPrefix = isIncome ? '+' : '-';
          
          // Determine transaction type badge
          let typeClass = '';
          switch (transaction.tradeType) {
            case 1:
              typeClass = 'transaction-type-recharge';
              break;
            case 2:
              typeClass = 'transaction-type-withdraw';
              break;
            case 3:
              typeClass = 'transaction-type-transfer';
              break;
            case 4:
              typeClass = 'transaction-type-payment';
              break;
            case 5:
              typeClass = 'transaction-type-refund';
              break;
          }
          
          // Determine status badge
          let statusClass = '';
          switch (transaction.status) {
            case 0:
              statusClass = 'transaction-status-processing';
              break;
            case 1:
              statusClass = 'transaction-status-success';
              break;
            case 2:
              statusClass = 'transaction-status-failed';
              break;
          }
          
          html += `
            <tr>
              <td>${transaction.tradeNo}</td>
              <td><span class="transaction-type-badge ${typeClass}">${transaction.tradeTypeName}</span></td>
              <td>${transaction.targetAccount || '-'}</td>
              <td>${Utils.formatDate(transaction.createTime, true)}</td>
              <td class="transaction-amount ${amountClass}">${amountPrefix}¥${Math.abs(transaction.amount).toFixed(2)}</td>
              <td>¥${transaction.balance.toFixed(2)}</td>
              <td><span class="transaction-status-badge ${statusClass}">${transaction.statusName}</span></td>
              <td>
                <button class="btn btn-sm btn-link view-detail" data-id="${transaction.id}">查看</button>
              </td>
            </tr>
          `;
        });
        
        transactionsList.innerHTML = html;
        
        // Add click event to view details
        const viewDetailBtns = document.querySelectorAll('.view-detail');
        viewDetailBtns.forEach(btn => {
          btn.addEventListener('click', () => {
            const id = btn.getAttribute('data-id');
            viewTransactionDetail(id);
          });
        });
      }
      
      // Render pagination
      function renderPagination() {
        if (totalPages <= 1) {
          pagination.innerHTML = '';
          return;
        }
        
        let html = '';
        
        // Previous page
        html += `
          <div class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage - 1}" ${currentPage === 1 ? 'tabindex="-1"' : ''}>
              <i class="fas fa-chevron-left"></i>
            </a>
          </div>
        `;
        
        // Page numbers
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, startPage + 4);
        
        for (let i = startPage; i <= endPage; i++) {
          html += `
            <div class="page-item ${i === currentPage ? 'active' : ''}">
              <a class="page-link" href="#" data-page="${i}">${i}</a>
            </div>
          `;
        }
        
        // Next page
        html += `
          <div class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage + 1}" ${currentPage === totalPages ? 'tabindex="-1"' : ''}>
              <i class="fas fa-chevron-right"></i>
            </a>
          </div>
        `;
        
        pagination.innerHTML = html;
        
        // Add click event to pagination links
        const pageLinks = document.querySelectorAll('.page-link');
        pageLinks.forEach(link => {
          link.addEventListener('click', (e) => {
            e.preventDefault();
            
            if (link.parentElement.classList.contains('disabled')) {
              return;
            }
            
            const page = parseInt(link.getAttribute('data-page'));
            currentPage = page;
            filterParams.page = currentPage;
            
            loadTransactions();
          });
        });
      }
      
      // View transaction detail
      function viewTransactionDetail(id) {
        ApiService.get(`/api/transaction/detail/${id}`)
          .then(response => {
            if (response.code === 0 && response.data) {
              const transaction = response.data;
              
              // Determine amount class (positive/negative)
              const isIncome = [1, 5].includes(transaction.tradeType); // 充值或退款
              const amountClass = isIncome ? 'amount-positive' : 'amount-negative';
              const amountPrefix = isIncome ? '+' : '-';
              
              // Update modal content
              detailAmount.className = `transaction-detail-amount ${amountClass}`;
              detailAmount.textContent = `${amountPrefix}¥${Math.abs(transaction.amount).toFixed(2)}`;
              detailTradeNo.textContent = transaction.tradeNo;
              detailTradeType.textContent = transaction.tradeTypeName;
              detailTarget.textContent = transaction.targetAccount || '-';
              detailChannel.textContent = transaction.channelName || transaction.channel || '-';
              detailTime.textContent = Utils.formatDate(transaction.createTime, true);
              detailStatus.textContent = transaction.statusName;
              detailBalance.textContent = `¥${transaction.balance.toFixed(2)}`;
              detailRemark.textContent = transaction.remark || '-';
              
              // Show modal
              detailModal.style.display = 'flex';
            } else {
              Toast.error(response.message || '获取交易详情失败');
            }
          })
          .catch(error => {
            console.error('Error loading transaction detail:', error);
            Toast.error('获取交易详情失败，请稍后再试');
          });
      }
      
      // Hide transaction detail modal
      function hideDetailModal() {
        detailModal.style.display = 'none';
      }
      
      // Apply filters
      searchBtn.addEventListener('click', () => {
        // Update filter params
        filterParams = {
          page: 1,
          size: pageSize
        };
        
        if (typeSelect.value) {
          filterParams.tradeType = typeSelect.value;
        }
        
        if (statusSelect.value) {
          filterParams.status = statusSelect.value;
        }
        
        if (startDateInput.value && endDateInput.value) {
          filterParams.startDate = `${startDateInput.value} 00:00:00`;
          filterParams.endDate = `${endDateInput.value} 23:59:59`;
        }
        
        // Reset current page
        currentPage = 1;
        
        // Load transactions with new filters
        loadTransactions();
      });
      
      // Reset filters
      resetBtn.addEventListener('click', () => {
        typeSelect.value = '';
        statusSelect.value = '';
        initDateInputs();
        
        // Reset filter params
        filterParams = {
          page: 1,
          size: pageSize
        };
        
        // Reset current page
        currentPage = 1;
        
        // Load transactions
        loadTransactions();
      });
      
      // Export transactions
      exportBtn.addEventListener('click', () => {
        Toast.info('正在准备导出数据，请稍候...');
        
        // In a real application, this would call the export API
        // For this demo, we'll just show a toast
        setTimeout(() => {
          Toast.success('导出成功，文件已下载');
        }, 2000);
      });
      
      // Modal close events
      detailClose.addEventListener('click', hideDetailModal);
      detailCloseBtn.addEventListener('click', hideDetailModal);
      
      // Close modal when clicking outside
      window.addEventListener('click', (e) => {
        if (e.target === detailModal) {
          hideDetailModal();
        }
      });
    });
  </script>
</body>
</html>
